package cn.dansj.common.utils.json;

import cn.dansj.common.utils.reflect.ClassUtils;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.Deserializers;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.util.Set;

class AutoDeserializeModule extends SimpleModule {
    private final String basePackage;

    public AutoDeserializeModule(String basePackage) {
        this.basePackage = basePackage;
    }

    @Override
    public void setupModule(SetupContext context) {
        super.setupModule(context);
        // 扫描指定包下所有带有@AutoDeserialize注解的类
        Set<Class<?>> annotatedClasses = ClassUtils.getClassWithAnnotation(AutoDeserialize.class, basePackage);
        // 为每个带注解的类注册通用反序列化器
        context.addDeserializers(new Deserializers.Base() {
            @Override
            public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException {
                Class<?> beanClass = beanDesc.getBeanClass();
                return annotatedClasses.contains(beanClass) ? new UniversalDeserializer<>(beanClass) : super.findBeanDeserializer(type, config, beanDesc);
            }
        });
    }
}